package com.ftg.learn.chapter12.springbootdemo.controller;

import com.alibaba.fastjson2.JSON;
import com.ftg.learn.chapter12.springbootdemo.entity.UserEntity;
import com.ftg.learn.chapter12.springbootdemo.service.UserService;
import com.ftg.learn.chapter12.springbootdemo.util.R;
import com.ftg.learn.chapter12.springbootdemo.vo.UserVo;
import com.github.pagehelper.PageInfo;
import org.apache.ibatis.annotations.Delete;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.Set;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author 布衣
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @Autowired
    StringRedisTemplate redisTemplate;

    Lock lock = new ReentrantLock();

    /**
     * 输入 模糊查询框，返回的带分页的表格数据
     * 50W  N 个人发起请求  ()
     * tomcat 200人并发  (。。。) 2000 【mysql I/O】
     * 9哥（....）
     * 5 1 5 台 (mybatis 内存机制) localcache(缓存)
     * <p>
     * redis (nosql 内存条 硬盘 1 81000 110000)
     * <p>
     * 10W 50
     *
     * @return
     */
    @GetMapping("/list")
    public String list(
            @RequestParam("page") Integer page, @RequestParam("pageSize") Integer pageSize) {
        //synchronized

        //存储到redis里面 【锁】
        try {
            lock.lock();
            String key = "user_list_" + page + "_" + pageSize;
            if (redisTemplate.opsForValue().get(key) == null) {
                //查询数据 库了
                R<PageInfo<UserVo>> list = userService.list(page, pageSize);
                redisTemplate.opsForValue().set(key,JSON.toJSONString(list),3000, TimeUnit.SECONDS);
            }
//            Set<String> keys  = redisTemplate.keys("user_list*");
//            String ks ="";
//            for(String k:keys){
//               ks+=k+" ";
//            }
//            redisTemplate.delete(ks);
            return redisTemplate.opsForValue().get(key);
        } finally {
            lock.unlock();
        }
    }

    /**
     *
     */
    @PostMapping("/save")
    public R<Integer> save(@RequestBody UserEntity ue) {
        return userService.save(ue);
    }

    @DeleteMapping("/delById/{id}")
    public R<Boolean> delete(@PathVariable("id") Integer id) {
        return userService.delById(id);
    }

    @PutMapping("/modify")
    public R<Boolean> modify(@RequestBody UserVo ue) {
        return userService.modify(ue);
    }
}
